import { ref } from 'vue'
import { supabase } from '../lib/supabase'
import type { User } from '../types/ui'

export const useUserData = () => {
  const loading = ref(false)
  const error = ref<string | null>(null)

  // 获取用户资料
  const getUserProfile = async (userId: string): Promise<User | null> => {
    loading.value = true
    error.value = null
    
    try {
      const { data, error: fetchError } = await supabase
        .from('user_profiles')
        .select('*')
        .eq('user_id', userId)
        .maybeSingle()

      if (fetchError) {
        console.error('Error fetching user profile:', fetchError)
        return null
      }

      if (!data) {
        return null
      }

      // 获取用户上传的电影数量
      const { count: movieCount } = await supabase
        .from('movies')
        .select('*', { count: 'exact', head: true })
        .eq('uploader_id', data.user_id)

      // 转换为前端User类型
      const user: User = {
        id: data.user_id,
        name: data.name,
        avatar: data.avatar_url,
        bio: data.bio,
        isAi: data.is_ai,
        followers: data.followers,
        following: data.following,
        uploads: movieCount || 0,
        createdAt: data.created_at
      }

      return user
    } catch (err) {
      console.error('Error in getUserProfile:', err)
      error.value = '获取用户资料失败'
      return null
    } finally {
      loading.value = false
    }
  }



  // 获取用户评论
  const getUserComments = async (userId: string, limit: number = 20, offset: number = 0) => {
    loading.value = true
    error.value = null
    
    try {
      // 获取评论数据（包括回复）
      const { data: commentsData, error: commentsError } = await supabase
        .from('comments')
        .select('*')
        .eq('user_id', userId)
        .order('created_at', { ascending: false })
        .range(offset, offset + limit - 1)

      if (commentsError) {
        console.error('Error fetching user comments:', commentsError)
        return []
      }

      if (!commentsData || commentsData.length === 0) {
        return []
      }

      // 获取所有电影ID
      const movieIds = [...new Set(commentsData.map(comment => comment.movie_id).filter(Boolean))]
      
      // 获取所有父评论ID
      const parentCommentIds = [...new Set(commentsData.map(comment => comment.parent_id).filter(Boolean))]
      console.log('Parent comment IDs:', parentCommentIds)
      
      // 批量获取电影信息
      let moviesData: any[] = []
      if (movieIds.length > 0) {
        const { data: movies, error: moviesError } = await supabase
          .from('movies')
          .select('id, title, cover_url')
          .in('id', movieIds)
        
        if (!moviesError && movies) {
          moviesData = movies
        }
      }

      // 批量获取父评论信息
      let parentCommentsData: any[] = []
      if (parentCommentIds.length > 0) {
        const { data: parentComments, error: parentError } = await supabase
          .from('comments')
          .select(`
            id,
            content,
            user_id
          `)
          .in('id', parentCommentIds)
        
        if (!parentError && parentComments) {
          parentCommentsData = parentComments
          console.log('Parent comments data:', parentCommentsData)
        } else {
          console.error('Error fetching parent comments:', parentError)
        }
      }

      // 获取父评论的用户信息
      const parentUserIds = [...new Set(parentCommentsData.map(comment => comment.user_id))]
      console.log('Parent user IDs:', parentUserIds)
      let parentUserProfiles: any[] = []
      if (parentUserIds.length > 0) {
        const { data: userProfiles, error: userError } = await supabase
          .from('user_profiles')
          .select('user_id, name, avatar_url, is_ai')
          .in('user_id', parentUserIds)
        
        if (!userError && userProfiles) {
          parentUserProfiles = userProfiles
          console.log('Parent user profiles:', parentUserProfiles)
        } else {
          console.error('Error fetching parent user profiles:', userError)
        }
      }

      // 创建用户信息映射
      const userProfileMap = new Map()
      parentUserProfiles.forEach(profile => {
        userProfileMap.set(profile.user_id, profile)
      })

      // 创建电影信息映射
      const movieMap = new Map()
      moviesData.forEach(movie => {
        movieMap.set(movie.id, movie)
      })

      // 创建父评论信息映射
      const parentCommentMap = new Map()
      parentCommentsData.forEach(parentComment => {
        const userProfile = userProfileMap.get(parentComment.user_id)
        parentCommentMap.set(parentComment.id, {
          id: parentComment.id,
          content: parentComment.content,
          user: {
            id: parentComment.user_id,
            name: userProfile?.name || '未知用户',
            avatar: userProfile?.avatar_url,
            isAi: userProfile?.is_ai || false
          }
        })
      })

      // 转换数据格式
      const comments = commentsData.map((comment) => {
        const movie = movieMap.get(comment.movie_id)
        const parentComment = parentCommentMap.get(comment.parent_id)
        
        return {
          id: comment.id,
          userId: comment.user_id,
          user: {
            id: comment.user_id,
            name: '我', // 这里可以获取用户信息
            avatar: undefined,
            isAi: false
          },
          content: comment.content,
          likes: comment.likes || 0,
          dislikes: comment.dislikes || 0,
          replies: [],
          createdAt: comment.created_at,
          updatedAt: comment.updated_at,
          parentId: comment.parent_id || undefined,
          parentComment: parentComment || undefined,
          movie: movie ? {
            id: movie.id,
            title: movie.title,
            coverUrl: movie.cover_url
          } : undefined
        }
      })

      return comments
    } catch (err) {
      console.error('Error in getUserComments:', err)
      error.value = '获取用户评论失败'
      return []
    } finally {
      loading.value = false
    }
  }

  // 获取用户统计信息
  const getUserStats = async (userId: string) => {
    try {
      // 获取电影数量
      const { count: movieCount } = await supabase
        .from('movies')
        .select('*', { count: 'exact', head: true })
        .eq('uploader_id', userId)

      // 获取评论数量
      const { count: commentCount } = await supabase
        .from('comments')
        .select('*', { count: 'exact', head: true })
        .eq('user_id', userId)

      return {
        movieCount: movieCount || 0,
        commentCount: commentCount || 0
      }
    } catch (err) {
      console.error('Error in getUserStats:', err)
      return {
        movieCount: 0,
        commentCount: 0
      }
    }
  }

  // 更新用户资料
  const updateUserProfile = async (userId: string, updates: Partial<User>) => {
    loading.value = true
    error.value = null
    
    try {
      const { data, error: updateError } = await supabase
        .from('user_profiles')
        .update({
          name: updates.name,
          bio: updates.bio,
          avatar_url: updates.avatar,
          updated_at: new Date().toISOString()
        })
        .eq('user_id', userId)
        .select()
        .maybeSingle()

      if (updateError) {
        console.error('Error updating user profile:', updateError)
        error.value = '更新用户资料失败'
        return null
      }

      return data
    } catch (err) {
      console.error('Error in updateUserProfile:', err)
      error.value = '更新用户资料失败'
      return null
    } finally {
      loading.value = false
    }
  }

  return {
    loading,
    error,
    getUserProfile,
    getUserComments,
    getUserStats,
    updateUserProfile
  }
} 